package xiaomogu.task_engine.admin.core.alarm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import xiaomogu.task_engine.admin.core.model.JobInfo;
import xiaomogu.task_engine.admin.core.model.JobLog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class Alarmer implements ApplicationContextAware, InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(Alarmer.class);

    private ApplicationContext applicationContext;
    private List<Alarm> alarmList;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Alarm> map = applicationContext.getBeansOfType(Alarm.class);
        if (map != null && map.size() > 0) {
            alarmList = new ArrayList<Alarm>(map.values());
        }
    }


    public boolean alarm(JobInfo jobInfo, JobLog jobLog) {

        boolean result = false;
        if (alarmList != null && alarmList.size() > 0) {
            result = true;  // success means all-success
            for (Alarm alarm : alarmList) {
                boolean resultItem = false;
                try {
                    resultItem = alarm.doAlarm(jobInfo, jobLog);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                if (!resultItem) {
                    result = false;
                }
            }
        }

        return result;
    }

}
